package com.hunantv.mglive.ui.live;


import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import mgtvcom.devsmart.android.ui.HorizontalListView;
import com.hunantv.mglive.R;
import com.hunantv.mglive.common.BaseFragment;
import com.hunantv.mglive.common.BuildConfig;
import com.hunantv.mglive.common.FormEncodingBuilderEx;
import com.hunantv.mglive.common.MaxApplication;
import com.hunantv.mglive.data.LiveDataModel;
import com.hunantv.mglive.data.LiveDetailModel;
import com.hunantv.mglive.data.ResultModel;
import com.hunantv.mglive.data.StarModel;
import com.hunantv.mglive.data.live.ChatData;
import com.hunantv.mglive.ui.adapter.LiveStarAdapter;
import com.hunantv.mglive.utils.DanMuUtil;
import com.hunantv.mglive.utils.GlideRoundTransform;
import com.hunantv.mglive.utils.L;
import com.hunantv.mglive.utils.NetworkUtils;
import com.hunantv.mglive.utils.PlayMessageUploadMannager;
import com.hunantv.mglive.utils.StringUtil;
import com.hunantv.mglive.utils.Toast;
import com.hunantv.mglive.widget.LiveMsgView;
import com.hunantv.mglive.widget.LoadingView;
import com.hunantv.mglive.widget.NotifyDialog;
import com.hunantv.mglive.widget.PersonValueAnim;
import com.hunantv.mglive.widget.VideoErrorView;
import com.hunantv.mglive.widget.media.IjkVideoView;
import com.hunantv.mglive.widget.media.VideoController;

import org.json.JSONObject;

import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import master.flame.danmaku.controller.DrawHandler;
import master.flame.danmaku.controller.IDanmakuView;
import master.flame.danmaku.danmaku.loader.ILoader;
import master.flame.danmaku.danmaku.loader.IllegalDataException;
import master.flame.danmaku.danmaku.loader.android.DanmakuLoaderFactory;
import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.DanmakuTimer;
import master.flame.danmaku.danmaku.model.IDisplayer;
import master.flame.danmaku.danmaku.model.android.DanmakuContext;
import master.flame.danmaku.danmaku.model.android.Danmakus;
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser;
import master.flame.danmaku.danmaku.parser.IDataSource;
import master.flame.danmaku.danmaku.parser.android.BiliDanmukuParser;
import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

import static com.hunantv.mglive.R.id.rl_live_detail_star_info;
import static com.hunantv.mglive.R.id.seekbar_live_detail_bottom_seek;


/**
 * A simple {@link BaseFragment} subclass.
 */
public class LiveDetailVideoFragment extends BaseFragment implements OnClickListener, IMediaPlayer.OnCompletionListener, IMediaPlayer.OnPreparedListener, NotifyDialog.onButtonClickListener, LiveStarAdapter.onStarItemClickListener, VideoErrorView.onRefreshClick, IMediaPlayer.OnErrorListener, Animation.AnimationListener, IMediaPlayer.OnInfoListener {
    private final String TAG = "LiveDetailVideoFragment";
    private static final int WHAT_CHANGE_KEY_ON_LINE = 1;
    private static final int WHAT_CHANGE_VIEW = 2;
    private static final int WHAT_STAR_LIST_SCROLL = 3;
    private long mCountTime;
    private int mWidth;
    private int mReTryTimes;
    private int mProgress;
    private String mVideoPath;
    private Boolean mIsAnim = false;
    private boolean mIsResume = true;
    //onPause时的视频播放状态
    private boolean mIsPlaying;
    //动态、人气、守护全屏前的视频播放状态
    private boolean mIsFullPlaying;
    private boolean mIsLandView;
    private boolean mHasNotify;
    private boolean mShowLoading;
    private boolean mIsDefaultView = true;
    private boolean mStartPalyer = true;

    private View mView;
    private ImageView mIvBg;
    private ImageButton mIbtnStart;
    private ImageButton mIbtnMargin;
    private ImageButton mIbtnGift;
    private IDanmakuView mDanmakuView;
    private IjkVideoView mVideoView;
    private LinearLayout mRvBottomView;

    private ImageView mIvPopularityIcon;
    private TextView mTvPopularityValuvalue;
    private LinearLayout mLlPopularity;

    private ViewHolder mViewHolder;
    private VideoController mController;
    private LiveMsgView mLiveMsgView;
    private LoadingView mLoadingView;
    private VideoErrorView mVideoErrorView;

    private LiveStarAdapter mAdapter;
    private StarModel mSelectedStarModel;
    private boolean mIsSelectFollow = false;//当前选择艺人是否粉
    //    private StarModel mAttentionStart;
    private List<StarModel> mStars = new ArrayList<>();

    private TranslateAnimation mAnimationUpToDown;
    private TranslateAnimation mAnimationUpToDownBack;
    private TranslateAnimation mAnimationDownToUp;
    private TranslateAnimation mAnimationDownToUpBack;

    private LiveDetailModel mDetailModel;
    private PersonValueAnim mPersonValueAnim;
    private IVideoViewCallBcak mIVideoViewCallBcak;

    private DanMuUtil mDanmuUtil;

    //视频卡顿上报类型，直播，点播
    private String upPlayVedioType;


    private Handler mHandler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {

            switch (msg.what) {
                case WHAT_CHANGE_KEY_ON_LINE:
                    String changeStr = msg.getData().getString("online");
                    Activity activity = getActivity();
                    if (activity != null && !activity.isFinishing() && !StringUtil.isNullorEmpty(changeStr) && !changeStr.equals("0") && !changeStr.equals("null")) {
                        if (mViewHolder.mTvOnline.getVisibility() != View.VISIBLE) {
                            mViewHolder.mTvOnline.setVisibility(View.VISIBLE);
                        }
                        mViewHolder.mTvOnline.setText(getString(R.string.live_online, changeStr));
                    }
                    break;
                case WHAT_CHANGE_VIEW:
                    if (!mIsDefaultView) {
                        mCountTime++;
                        if (mCountTime >= 5 && mIsResume) {
                            changeView(false);
                        } else {
                            mHandler.sendEmptyMessageDelayed(WHAT_CHANGE_VIEW, 1000);
                        }
                    }
                    break;
                case WHAT_STAR_LIST_SCROLL:
                    mViewHolder.mHlvStars.requestLayout();
                    break;
                default:
                    break;
            }
            return false;
        }
    });

    public LiveDetailVideoFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_live_detail_video, container, false);
        initView(mView);
        initAnim();
        mPersonValueAnim = new PersonValueAnim(getContext(), (ViewGroup) mView);
        return mView;
    }

    private void initView(View view) {
        mVideoView = (IjkVideoView) view.findViewById(R.id.sfv_star_detail_live_video);
        mIvBg = (ImageView) view.findViewById(R.id.iv_live_detail_bg);
        mIbtnStart = (ImageButton) view.findViewById(R.id.ibtn_live_detail_wifi_pause);
        mRvBottomView = (LinearLayout) view.findViewById(R.id.ll_live_detail_bottom_info);

        mIbtnGift = (ImageButton) view.findViewById(R.id.ibtn_live_full_screen_gif);
        mIbtnMargin = (ImageButton) view.findViewById(R.id.gift_layout);

        mDanmakuView = (IDanmakuView) view.findViewById(R.id.sv_danmaku);
        mLlPopularity = (LinearLayout) view.findViewById(R.id.ll_live_full_screen_popularity);
        mTvPopularityValuvalue = (TextView) view.findViewById(R.id.tv_live_full_popularity);
        mIvPopularityIcon = (ImageView) view.findViewById(R.id.iv_live_full_screen_popularity_icon);

        mIbtnGift.setOnClickListener(this);
        mVideoView.setOnClickListener(this);
        mVideoView.setOnCompletionListener(this);
        mVideoView.setOnPreparedListener(this);
        mVideoView.setOnErrorListener(this);
        mVideoView.setOnInfoListener(this);
        mIbtnStart.setOnClickListener(this);

        changeLayouParams();
        initHolderView(view);
        setDanmuView();
    }

    private void changeLayouParams() {
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        mWidth = dm.widthPixels;
        mVideoErrorView = new VideoErrorView(getActivity(), mWidth, (int) (mWidth * 0.75));
        if (mIsLandView) {
            FrameLayout.LayoutParams ps = (FrameLayout.LayoutParams) mVideoView.getLayoutParams();
            //按比例缩放直播窗体
            ps.height = dm.heightPixels;
            ps.width = dm.widthPixels;
            mVideoView.setLayoutParams(ps);
            mVideoView.refreshParams(dm.widthPixels, dm.heightPixels);

            FrameLayout.LayoutParams psBg = (FrameLayout.LayoutParams) mIvBg.getLayoutParams();
            psBg.height = FrameLayout.LayoutParams.MATCH_PARENT;
            psBg.width = FrameLayout.LayoutParams.MATCH_PARENT;
            mIvBg.setLayoutParams(psBg);
        } else {
            int width = dm.widthPixels > dm.heightPixels ? dm.heightPixels : dm.widthPixels;
            FrameLayout.LayoutParams ps = (FrameLayout.LayoutParams) mVideoView.getLayoutParams();
//            //按比例缩放直播窗体
            int liveViewHight = (int) (width * 0.75f);  // 4:3
            ps.height = liveViewHight;
            mVideoView.setLayoutParams(ps);
            mVideoView.setViewParams(mWidth, liveViewHight);
            mVideoView.refreshParams(mWidth, liveViewHight);

            FrameLayout.LayoutParams psBg = (FrameLayout.LayoutParams) mIvBg.getLayoutParams();
            psBg.height = liveViewHight;
            psBg.width = mWidth;
            mIvBg.setLayoutParams(psBg);
        }
    }

    private void initHolderView(View view) {
        mViewHolder = new ViewHolder();
        mViewHolder.mTvOnline = (TextView) view.findViewById(R.id.tv_live_detail_online_num_text);
        mViewHolder.mLlOnline = (LinearLayout) view.findViewById(R.id.ll_live_detail_onlie);
        mViewHolder.mBtnAttention = (Button) view.findViewById(R.id.btn_live_detail_star_attention);
        mViewHolder.mBtnAttention.setOnClickListener(this);
        mViewHolder.mRlStarInfo = (RelativeLayout) view.findViewById(rl_live_detail_star_info);
        mViewHolder.mIvIcon = (ImageView) view.findViewById(R.id.iv_live_detail_icon);
        mViewHolder.mTvName = (TextView) view.findViewById(R.id.tv_live_detail_star_name);
        mViewHolder.mIvTag = (ImageView) view.findViewById(R.id.iv_live_detail_star_tag);
        mViewHolder.mTvRanking = (TextView) view.findViewById(R.id.tv_live_detail_star_ranking);
        mViewHolder.mTvRankingDistance = (TextView) view.findViewById(R.id.tv_live_detail_star_ranking_distance);
        mViewHolder.mLlRank = (LinearLayout) view.findViewById(R.id.ll_live_detail_rank);
        mViewHolder.mHlvStars = (HorizontalListView) view.findViewById(R.id.hlv_live_detail_bottom_stars);
        mViewHolder.mLlSeekbar = (LinearLayout) view.findViewById(R.id.ll_live_detail_bottom_seekbar);
        mViewHolder.mIbtnPause = (ImageButton) view.findViewById(R.id.ibtn_live_detail_bootm_pause);
        mViewHolder.mTvCurrTime = (TextView) view.findViewById(R.id.tv_live_detail_bottom_curr_time);
        mViewHolder.mSeekbar = (SeekBar) view.findViewById(seekbar_live_detail_bottom_seek);
        mViewHolder.mTvEndTime = (TextView) view.findViewById(R.id.tv_live_detail_bottom_end_time);
        mAdapter = new LiveStarAdapter(getActivity(), mStars);
        mAdapter.setOnClickListener(this);
        mViewHolder.mHlvStars.setAdapter(mAdapter);
        mViewHolder.mHlvStars.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                LiveStarAdapter adapter = (LiveStarAdapter) parent.getAdapter();
                StarModel model = adapter.getItem(position);
                if (model == null || StringUtil.isNullorEmpty(model.getUid()) || model.getUid().equals(mSelectedStarModel.getUid())) {
                    return;
                }
                changeStar(adapter, model);
            }
        });
        mViewHolder.mHlvStars.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_MOVE) {
                    mHandler.removeMessages(WHAT_CHANGE_VIEW);
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    mHandler.sendEmptyMessageDelayed(WHAT_CHANGE_VIEW, 1000);
                }
                return false;
            }
        });
        mController = new VideoController(getContext());
        mVideoView.setController(mController);
        mController.initControllerView(mViewHolder.mIbtnPause, mViewHolder.mSeekbar, mViewHolder.mTvCurrTime, mViewHolder.mTvEndTime);
        mController.setSeekBarTouchListener(new VideoController.onSeekBarTouch() {
            @Override
            public void onTouchStart() {
                mHandler.removeMessages(WHAT_CHANGE_VIEW);
            }

            @Override
            public void onTouchEnd() {
                mCountTime = 0;
                mHandler.sendEmptyMessageDelayed(WHAT_CHANGE_VIEW, 1000);
            }
        });
        mViewHolder.mFlMsg = (FrameLayout) view.findViewById(R.id.fl_live_detail_msg);
        mLiveMsgView = new LiveMsgView(getActivity(), mWidth, mViewHolder.mFlMsg);
        mLoadingView = new LoadingView(getActivity(), (ViewGroup) mView);
        mVideoErrorView = new VideoErrorView(getActivity(), mWidth, (int) (mWidth * 0.75));
        mVideoErrorView.setonRefreshListener(this);
    }

    private void changeStar(LiveStarAdapter adapter, StarModel model) {
        adapter.changeCheckStar(model);
        adapter.notifyDataSetChanged();
        mCountTime = 0;
        mSelectedStarModel = model;
        changeStar(mSelectedStarModel);
        Toast.makeText(getActivity(), getString(R.string.live_start_change, mSelectedStarModel.getNickName()), Toast.LENGTH_SHORT).show();
        if (mIVideoViewCallBcak != null) {
            mIVideoViewCallBcak.changeStar(model);
        }
        updateFollowStatus();
    }

    private void initAnim() {
        mAnimationUpToDown = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1, Animation.RELATIVE_TO_SELF, 0);
        mAnimationUpToDown.setDuration(300);
        mAnimationUpToDown.setAnimationListener(this);
        mAnimationUpToDownBack = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -2);
        mAnimationUpToDownBack.setDuration(300);
        mAnimationUpToDownBack.setAnimationListener(this);
        mAnimationDownToUp = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1, Animation.RELATIVE_TO_SELF, 0);
        mAnimationDownToUp.setDuration(300);
        mAnimationDownToUpBack = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1);
        mAnimationDownToUpBack.setDuration(300);
        mAnimationDownToUpBack.setAnimationListener(this);
    }

    private void setDanmuView() {
        // 设置最大显示行数
        HashMap<Integer, Integer> maxLinesPair = new HashMap<>();
        maxLinesPair.put(BaseDanmaku.TYPE_SCROLL_RL, 6); // 滚动弹幕最大显示6行
        // 设置是否禁止重叠
        HashMap<Integer, Boolean> overlappingEnablePair = new HashMap<>();
        overlappingEnablePair.put(BaseDanmaku.TYPE_SCROLL_RL, true);

        DanmakuContext mContext = DanmakuContext.create();
        mContext.setDanmakuStyle(IDisplayer.DANMAKU_STYLE_STROKEN, 3).setDuplicateMergingEnabled(false).setScrollSpeedFactor(1.2f).setScaleTextSize(1.2f)
//        .setCacheStuffer(new BackgroundCacheStuffer())  // 绘制背景使用BackgroundCacheStuffer
                .setMaximumLines(maxLinesPair)
                .preventOverlapping(overlappingEnablePair);

        BaseDanmakuParser mParser = createParser(this.getResources().openRawResource(R.raw.comments));
        mDanmuUtil = new DanMuUtil(mContext, mDanmakuView, mParser);
        mDanmakuView.setCallback(new DrawHandler.Callback() {
            @Override
            public void updateTimer(DanmakuTimer timer) {
            }

            @Override
            public void drawingFinished() {

            }

            @Override
            public void danmakuShown(BaseDanmaku danmaku) {
//                    Log.d("DFM", "danmakuShown(): text=" + danmaku.text);
            }

            @Override
            public void prepared() {
                mDanmakuView.start();
            }
        });
        mDanmakuView.prepare(mParser, mContext);
        mDanmakuView.enableDanmakuDrawingCache(true);
//        mDanmuHandler.sendEmptyMessageDelayed(MSG_TYPE_CHECK_DISPLAY, 500);
    }


    private BaseDanmakuParser createParser(InputStream stream) {
        if (stream == null) {
            return new BaseDanmakuParser() {

                @Override
                protected Danmakus parse() {
                    return new Danmakus();
                }
            };
        }
        ILoader loader = DanmakuLoaderFactory.create(DanmakuLoaderFactory.TAG_BILI);
        BaseDanmakuParser parser = new BiliDanmukuParser();
        if (loader != null) {
            try {

                loader.load(stream);
            } catch (IllegalDataException e) {
                e.printStackTrace();
            }
            IDataSource<?> dataSource = loader.getDataSource();
            parser.load(dataSource);
        }
        return parser;
    }

    private void setTagView(boolean island) {
        if (island) {
            mViewHolder.mLlOnline.setVisibility(View.GONE);
            if (mIsDefaultView) {
                mLlPopularity.setVisibility(View.VISIBLE);
            } else {
                mLlPopularity.setVisibility(View.INVISIBLE);
            }
        } else {
            if (mIsDefaultView) {
                mViewHolder.mLlOnline.setVisibility(View.VISIBLE);
            } else {
                mViewHolder.mLlOnline.setVisibility(View.GONE);
            }
            mLlPopularity.setVisibility(View.GONE);
        }
    }


    private void changeStar(StarModel user) {
        if (user == null) {
            return;
        }
        Glide.with(this).load(user.getPhoto())
                .placeholder(R.drawable.default_icon_preload).error(R.drawable.default_icon)
                .transform(new GlideRoundTransform(getActivity(), R.dimen.height_30dp)).into(mIvPopularityIcon);
        mTvPopularityValuvalue.setText(user.getHotValue());
    }

    private void setView(LiveDetailModel liveDetail, boolean hasCamera) {
        if (liveDetail == null) {
            return;
        }
        List<StarModel> stars = liveDetail.getUsers();
        if (stars != null && (stars.size() > 1 || hasCamera)) {
            mStars.clear();
            mStars.addAll(stars);
            mAdapter.notifyDataSetChanged();
            mViewHolder.mHlvStars.setVisibility(View.VISIBLE);
            mHandler.sendEmptyMessageDelayed(WHAT_STAR_LIST_SCROLL, 100);
            mViewHolder.mBtnAttention.setVisibility(View.GONE);
            mViewHolder.mRlStarInfo.setVisibility(View.GONE);
        } else if (stars != null && stars.size() > 0) {
            mViewHolder.mRlStarInfo.setVisibility(View.VISIBLE);
            mViewHolder.mHlvStars.setVisibility(View.GONE);
            StarModel star = stars.get(0);
            mViewHolder.mTvName.setText(star.getNickName());
            if (!StringUtil.isNullorEmpty(star.getRank())) {
                mViewHolder.mTvRanking.setText(star.getRank());
                mViewHolder.mTvRanking.setVisibility(View.VISIBLE);
            } else {
                mViewHolder.mTvRanking.setVisibility(View.GONE);
            }
            mViewHolder.mTvRankingDistance.setText("(距上一名还有82)");
            mViewHolder.mTvRankingDistance.setVisibility(View.GONE);
            mViewHolder.mBtnAttention.setVisibility(View.VISIBLE);
            Glide.with(this).load(star.getPhoto())
                    .placeholder(R.drawable.default_icon_preload).error(R.drawable.default_icon)
                    .transform(new GlideRoundTransform(getActivity(), R.dimen.height_35dp)).into(mViewHolder.mIvIcon);
        } else {
            mViewHolder.mBtnAttention.setVisibility(View.GONE);
        }
        if (mViewHolder.mTvRankingDistance.getVisibility() == View.GONE && mViewHolder.mTvRanking.getVisibility() == View.GONE) {
            mViewHolder.mLlRank.setVisibility(View.GONE);
        }
        if (liveDetail.getType().equals(LiveDetailModel.TYPE_BACK)) {
            mViewHolder.mLlSeekbar.setVisibility(View.VISIBLE);
        } else {
            mViewHolder.mLlSeekbar.setVisibility(View.GONE);
        }
        Glide.with(this).load(mDetailModel.getImage()).override(mWidth, (int) (mWidth * 0.75))
                .into(mIvBg);
    }

    private void updateFollowStatus() {
        mIsSelectFollow = false;//重置当前选择艺人是否已粉状态
        if (isLogin()) {
            Map<String, String> param = new FormEncodingBuilderEx()
                    .add("uid", MaxApplication.getInstance().getUid())
                    .add("token", MaxApplication.getInstance().getToken())
                    .add("artistId", mSelectedStarModel != null ? mSelectedStarModel.getUid() : "").build();
            post(BuildConfig.URL_GET_IS_FOLLOWED, param);
        }
    }

    public void setDetailModel(LiveDetailModel detailModel, String videoPath, boolean hasCamera) {
        mDetailModel = detailModel;
        mProgress = 0;
        if (mAdapter != null) {
            if (hasCamera) {
                mAdapter.showAoutChangeTag();
            }
            mAdapter.changeCheckStar(null);
        }
        List<StarModel> users = mDetailModel.getUsers();
        if (users != null && users.size() > 0) {
            mSelectedStarModel = users.get(0);
            changeStar(mSelectedStarModel);
            if (mIVideoViewCallBcak != null) {
                mIVideoViewCallBcak.changeStar(mSelectedStarModel);
            }
        }
        setView(mDetailModel, hasCamera);
        updateFollowStatus();
        if (mIsDefaultView) {
            changeView(false);
        } else {
            mCountTime = 0;
        }
        if (!StringUtil.isNullorEmpty(videoPath)) {
            mVideoPath = videoPath;
            startVideo(mVideoPath);
        }
    }


    private void startVideo(String videoPath) {
        if (StringUtil.isNullorEmpty(videoPath)) {  //maxxiang fix crash. videoPath不能为空
            return;
        }
        if (!NetworkUtils.isWifi()
                && !mHasNotify
                && getActivity() != null
                && !getActivity().isFinishing()) {
            NotifyDialog dialog = new NotifyDialog(getActivity());
            dialog.setOnButtonClickListener(this);
            dialog.show(mVideoPath);
        } else {
            setVideoPath(videoPath);
            mVideoView.requestFocus();
            if (mProgress > 0) {
                mVideoView.seekTo(mProgress);
                mProgress = 0;
            }
            mVideoView.start();


            String mType = mDetailModel.getType();
            if(mType == LiveDataModel.TYPE_LIVE){//直播
                upPlayVedioType = "1";
            }else if(mType == LiveDataModel.TYPE_BACK){//点播
                upPlayVedioType = "0";
            }else{//默认
                upPlayVedioType = "0";
            }

            Log.i("PlayStadus", "start");
            //开启上报卡顿信息
            String host = StringUtil.getUrlHost(videoPath);
            String path = "";
            if(!StringUtil.isNullorEmpty(host)){
                path = videoPath.substring(host.length()+7);
            }
            try {
                path = URLEncoder.encode(path, "UTF-8");
            }catch (Exception e){
                e.printStackTrace();
            }
            PlayMessageUploadMannager.getInstance().startUploadMessage(host, path, upPlayVedioType);
        }
    }

    private void setVideoPath(String videoPath) {
        Map<String, String> params = new HashMap<>();
        if (LiveDetailModel.TYPE_LIVE.equals(mDetailModel.getType())) {
            params.put("rmid", mDetailModel.getlId());
            params.put("chid", mDetailModel.getVideo());
            params.put("ap", "1");
            mVideoView.setVideoPath(videoPath, params, IjkVideoView.VideoType.act);
        } else {

            if(mSelectedStarModel!=null){
                params.put("auid", mSelectedStarModel.getUid());
            }else{
                params.put("auid", "");
            }

            params.put("mid", mDetailModel.getVideo());
            params.put("ap", "1");
            mVideoView.setVideoPath(videoPath, params, IjkVideoView.VideoType.vod);
        }


    }

    private void changeView(boolean isClick) {
        synchronized (mIsAnim) {
            if (!mIsAnim) {
                boolean result = true;
                if (mIsDefaultView) {
                    if (mIVideoViewCallBcak != null) {
                        result = mIVideoViewCallBcak.changeTitle(true, isClick);
                    }
                    if (result) {
                        mIsAnim = true;
                        mRvBottomView.clearAnimation();
                        mRvBottomView.startAnimation(mAnimationDownToUp);
                        if (!mIsLandView) {
                            mViewHolder.mLlOnline.clearAnimation();
                            mViewHolder.mLlOnline.startAnimation(mAnimationDownToUpBack);
                        } else {
                            mLlPopularity.clearAnimation();
                            mLlPopularity.startAnimation(mAnimationUpToDownBack);
                        }
                    }
                } else {
                    if (mIVideoViewCallBcak != null) {
                        result = mIVideoViewCallBcak.changeTitle(false, isClick);
                    }
                    if (result) {
                        mIsAnim = true;
                        mRvBottomView.clearAnimation();
                        mRvBottomView.startAnimation(mAnimationDownToUpBack);
                        if (!mIsLandView) {
                            mViewHolder.mLlOnline.clearAnimation();
                            mViewHolder.mLlOnline.startAnimation(mAnimationDownToUp);
                        } else {
                            mLlPopularity.clearAnimation();
                            mLlPopularity.startAnimation(mAnimationUpToDown);
                        }
                    }
                }
            }
        }
    }


    private void changeViewVisibility() {
        synchronized (mIsAnim) {
            if (!mIsAnim) {
                return;
            }
            mIsAnim = false;
            if (mIsDefaultView) {
                mCountTime = 0;
                mHandler.sendEmptyMessageDelayed(WHAT_CHANGE_VIEW, 1000);
                mController.show();
            } else {
                mController.hide();
            }
            mIsDefaultView = !mIsDefaultView;
        }
    }


    private void showLoadingView() {
        Activity activity = getActivity();
        if (activity != null && !activity.isFinishing()) {
//            mLoadingView.showAtLocation(mView, Gravity.TOP, 0, (int) (mWidth * 0.75 / 2));
            mLoadingView.showAtLocation();
        }
    }

    private void showVideoErrorView() {
        if (getActivity() == null || getActivity().isFinishing()) {
            return;
        }
        mVideoErrorView.showAtLocation(mView, Gravity.TOP, 0, 0);
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        IjkMediaPlayer.loadLibrariesOnce(null);
        IjkMediaPlayer.native_profileBegin("libijkplayer.so");
    }

    @Override
    public void onResume() {
        super.onResume();
        mIsResume = true;
        mLiveMsgView.onResume();
        if (!mShowLoading) {
            mShowLoading = true;
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (mVideoView != null && !mVideoView.isPlaying() && NetworkUtils.hasNetwork()) {
                        showLoadingView();
                    }
                }
            }, 1000);
        }
        L.d(TAG, "onResume   mIsPlaying="+mIsPlaying +"     mProgress="+mProgress);
        //只有暂停才不播放
        if (mIsPlaying || mProgress == 0) {
            if (mVideoView != null && !StringUtil.isNullorEmpty(mVideoPath)) {
                startVideo(mVideoPath);
            }
        }
    }


    @Override
    public void onPause() {
        super.onPause();
        mIsResume = false;
        if (mVideoView != null) {
            mIsPlaying = mVideoView.isPlaying();
            if (mDetailModel != null && LiveDetailModel.TYPE_BACK.equals(mDetailModel.getType())) {
                mProgress = mVideoView.getCurrentPosition();
                L.d(TAG, "onPause   mProgress="+mProgress);
            }
        }
        mLiveMsgView.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        L.d(TAG, "onStop");
        if (mVideoView != null && mVideoView.isPlaying()) {
            if (!mVideoView.isBackgroundPlayEnabled()) {
                L.d(TAG, "onStop   mVideoView.onStop");
                mVideoView.release(true);
                mVideoView.stopPlayback();
                mVideoView.stopBackgroundPlay();
                IjkMediaPlayer.native_profileEnd();

                //停止视频卡顿信息上报
                PlayMessageUploadMannager.getInstance().stopUploadMessage();
                //完成上报
                PlayMessageUploadMannager.getInstance().doneUpMessage();

            } else {
                mVideoView.enterBackground();
            }
        }else{
            L.d(TAG, "onStop   mVideoView.pause");
            mVideoView.pause();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mDanmakuView != null) {
            // dont forget release!
            mDanmakuView.release();
            mDanmakuView = null;
        }
        if (mController != null) {
            mController.onDestory();
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        mIVideoViewCallBcak = null;
    }

    @Override
    public void onClick(View v) {
            if(v.getId() == R.id.btn_live_detail_star_attention){
                if (!mIsDefaultView) {
                    if (!isLogin()) {
                        jumpToLogin("登录以后才可以粉TA哦~");
                        return;
                    }
                    if (mSelectedStarModel != null) {
                        if (!mIsSelectFollow) {
                            mCountTime = 0;
                            Map<String, String> body = new FormEncodingBuilderEx().add("uid", getUserInfo().getUid()).add("token", getUserInfo().getToken()).add("followid", mSelectedStarModel.getUid()).build();
                            post(BuildConfig.URL_ADD_FOLLOW, body);
                            mPersonValueAnim.startPersonValueAnim(v);
                        } else {
                            mCountTime = 0;
                            Map<String, String> body = new FormEncodingBuilderEx().add("uid", getUserInfo().getUid()).add("token", getUserInfo().getToken()).add("followid", mSelectedStarModel.getUid()).build();
                            post(BuildConfig.URL_REMOVE_FOLLOW, body);
                        }
                    }
                } else {
                    changeView(true);
                }
            }else if(v.getId() == R.id.sfv_star_detail_live_video){
                changeView(true);
            }else if(v.getId() == R.id.ibtn_live_detail_wifi_pause){
                startVideo(mVideoPath);
                mIbtnStart.setVisibility(View.GONE);
                mStartPalyer = true;
                showLoadingView();
            }else if(v.getId() == R.id.ibtn_live_full_screen_gif){
                if (!isLogin()) {
                    jumpToLogin("登录以后才可以送礼哦~");
                } else if (mIVideoViewCallBcak != null) {
                    mIVideoViewCallBcak.showGift();
                }
            }
    }

    @Override
    public void onError(String url, Exception e) {
        super.onError(url, e);
    }

    @Override
    public void onFailure(String url, ResultModel resultModel) {
        super.onFailure(url, resultModel);

    }

    @Override
    public void onSucceed(String url, ResultModel resultModel) {
        if (url.contains(BuildConfig.URL_REMOVE_FOLLOW)) {
            updateFollowStatus();
        } else if (url.contains(BuildConfig.URL_ADD_FOLLOW)) {
            updateFollowStatus();
        } else if (BuildConfig.URL_GET_IS_FOLLOWED.equals(url)) {
            try {
                JSONObject jsonData = new JSONObject(resultModel.getData());
                boolean isFollow = jsonData.getBoolean("isFollowed");
                mIsSelectFollow = isFollow;
                if (!isFollow) {
                    mViewHolder.mBtnAttention.setSelected(false);
                    mViewHolder.mBtnAttention.setText(getString(R.string.attention));
                } else {
                    mViewHolder.mBtnAttention.setSelected(true);
                    mViewHolder.mBtnAttention.setText(mSelectedStarModel.getFans());
                }
                if (mSelectedStarModel != null) {
                    mSelectedStarModel.setIsfans(Boolean.toString(isFollow));
                }
                if (mAdapter != null) {
                    mAdapter.notifyDataSetChanged();
                }
            } catch (Exception e) {

            }
        }
        super.onSucceed(url, resultModel);
    }

    @Override
    public Object asyncExecute(String url, ResultModel resultModel) {
        return super.asyncExecute(url, resultModel);
    }

    @Override
    public void onCompletion(IMediaPlayer mp) {
        L.d(TAG, "onCompletion   isVisible=" + isVisible()+"");
        if (mDetailModel != null) {
            startVideo(mVideoPath);
            if (LiveDetailModel.TYPE_LIVE.equals(mDetailModel.getType())) {
                mReTryTimes++;
            }
        }

        //停止视频卡顿信息上报
        PlayMessageUploadMannager.getInstance().stopUploadMessage();
        //完成上报
        PlayMessageUploadMannager.getInstance().doneUpMessage();
    }

    @Override
    public void onPrepared(IMediaPlayer mp) {

        mLoadingView.dismiss();
        mVideoErrorView.dismiss();
        mReTryTimes = 0;
    }

    @Override
    public boolean onError(IMediaPlayer mp, int what, int extra) {

        //出错上报
        PlayMessageUploadMannager.getInstance().errUpMessage(what,extra);

        Log.i("LiveVideo","OnErr");

        if (mReTryTimes < 3) {
            mReTryTimes++;
            startVideo(mVideoPath);
            mLoadingView.showAtLocation();
        } else {
            showVideoErrorView();
            mLoadingView.dismiss();
        }
        return false;
    }

    @Override
    public synchronized boolean onInfo(IMediaPlayer mp, int what, int extra) {
        switch (what) {
            case IMediaPlayer.MEDIA_INFO_BUFFERING_START:
                mLoadingView.showAtLocation();

                Log.i("LiveVideo", "OnPuse");
                PlayMessageUploadMannager.getInstance().addPuseCount();
                break;
            case IMediaPlayer.MEDIA_INFO_BUFFERING_END:
                mLoadingView.dismiss();

                PlayMessageUploadMannager.getInstance().doErrCount();
                break;
        }
        return false;
    }

    @Override
    public void onSure(String videoPath) {
        if (mVideoView != null && !StringUtil.isNullorEmpty(videoPath)) {
            setVideoPath(videoPath);
            mVideoView.requestFocus();
            mVideoView.start();

            String mType = mDetailModel.getType();
            if(mType == LiveDataModel.TYPE_LIVE){//直播
                upPlayVedioType = "1";
            }else if(mType == LiveDataModel.TYPE_BACK){//点播
                upPlayVedioType = "0";
            }else{//默认
                upPlayVedioType = "0";
            }

            Log.i("PlayStadus", "start");
            //开启上报卡顿信息
            String host = StringUtil.getUrlHost(videoPath);
            String path = "";
            if(!StringUtil.isNullorEmpty(host)){
                path = videoPath.substring(host.length()+7);
            }
            try {
                path = URLEncoder.encode(path, "UTF-8");
            }catch (Exception e){
                e.printStackTrace();
            }
            PlayMessageUploadMannager.getInstance().startUploadMessage(host, path, upPlayVedioType);
        }
        mHasNotify = true;
        mStartPalyer = true;
    }

    @Override
    public void onCancel() {
        mHasNotify = true;
        mStartPalyer = false;
        mLoadingView.dismiss();
        mIbtnStart.setVisibility(View.VISIBLE);
    }

    @Override
    public void onClick(StarModel starModel, View view) {
        if (!isLogin()) {
            jumpToLogin("登录以后才可以粉TA哦~");
            return;
        }
        if (starModel != null) {
            if (!mIsSelectFollow) {
                mCountTime = 0;
                Map<String, String> body = new FormEncodingBuilderEx()
                        .add("uid", getUserInfo().getUid())
                        .add("token", getUserInfo().getToken())
                        .add("followid", starModel.getUid()).build();
                post(BuildConfig.URL_ADD_FOLLOW, body);
                mPersonValueAnim.startPersonValueAnim(view);
            } else {
                mCountTime = 0;
                Map<String, String> body = new FormEncodingBuilderEx()
                        .add("uid", getUserInfo().getUid())
                        .add("token", getUserInfo().getToken())
                        .add("followid", starModel.getUid()).build();
                post(BuildConfig.URL_REMOVE_FOLLOW, body);
            }
        }
    }

    @Override
    public void onRefreshClick() {
        startVideo(mVideoPath);
        showLoadingView();
        mVideoErrorView.dismiss();
    }


    @Override
    public void onAnimationStart(Animation animation) {

    }

    @Override
    public void onAnimationEnd(Animation animation) {
        if (animation == mAnimationUpToDown) {
            mLlPopularity.setVisibility(View.VISIBLE);
        } else if (animation == mAnimationUpToDownBack) {
            mLlPopularity.setVisibility(View.INVISIBLE);
            mRvBottomView.setVisibility(View.VISIBLE);
        } else if (animation == mAnimationDownToUpBack) {
            if (mIsLandView) {
                mRvBottomView.setVisibility(View.INVISIBLE);
            } else {
                if (mIsDefaultView) {
                    mRvBottomView.setVisibility(View.VISIBLE);
                    mViewHolder.mLlOnline.setVisibility(View.INVISIBLE);
                } else {
                    mRvBottomView.setVisibility(View.INVISIBLE);
                    mViewHolder.mLlOnline.setVisibility(View.VISIBLE);
                }
            }
        }
        changeViewVisibility();
    }

    @Override
    public void onAnimationRepeat(Animation animation) {

    }

    public void setCountTime(int time) {
        mCountTime = time;
    }

    public void setVideoViewCallBack(IVideoViewCallBcak l) {
        mIVideoViewCallBcak = l;
    }

    public void onBackPressed() {
        if (mDanmakuView != null) {
            // dont forget release!
            mDanmakuView.release();
            mDanmakuView = null;
        }
    }

    public void pauseVideo() {
        if (mVideoView != null) {
            if (mDetailModel != null && LiveDetailModel.TYPE_BACK.equals(mDetailModel.getType())) {
                mProgress = mVideoView.getCurrentPosition();
            }
            mIsFullPlaying = mVideoView.isPlaying();
            mVideoView.pause();

        } else {
            mIsFullPlaying = false;
        }
    }

    public void starVideo() {
        if (!mVideoView.isPlaying() && mIsFullPlaying) {
            startVideo(mVideoPath);
        }
    }

    /**
     * 处理推送过来的消息，一种是喊话，一种是切换直播艺人
     *
     * @param chatData chatData
     */
    public void doMsg(ChatData chatData) {
        if (chatData == null) {
            return;
        }
        if (chatData.getType() == ChatData.CHAT_TYPE_DANMO || chatData.getType() == ChatData.CHAT_TYPE_CONTENT) {
            if (mIsLandView) {
                if (mDanmuUtil != null && !StringUtil.isNullorEmpty(chatData.getBarrageContent())) {
                    mDanmuUtil.addDanmu(chatData.getBarrageContent());
                }
            }
        } else if (chatData.getType() == ChatData.CHAT_TYPE_GIFT) {
            if (mLiveMsgView != null) {
                mLiveMsgView.displayView(chatData);
            }
        } else if (chatData.getType() == ChatData.CHAT_TYPE_STAR_CHANGE) {
            if (mDetailModel != null && chatData.getRoomId().equals(mDetailModel.getlId()) && chatData.getShowOwners() != null && !chatData.getShowOwners().isEmpty()) {
                String uid = chatData.getShowOwners().get(0).getUid();
                for (StarModel model : mStars) {
                    if (model.getUid().equals(uid)) {
                        StarModel firstStar = mStars.get(0);
                        if (mSelectedStarModel != null && mSelectedStarModel.getUid().equals(firstStar.getUid())) {
                            mSelectedStarModel = model;
                            Toast.makeText(getActivity(), getString(R.string.live_start_change, mSelectedStarModel.getNickName()), Toast.LENGTH_SHORT).show();
                        }
                        mStars.remove(model);
                        mStars.add(0, model);
                        if (mSelectedStarModel != null && !StringUtil.isNullorEmpty(mSelectedStarModel.getUid()) && mSelectedStarModel.getUid().equals(model.getUid())) {
                            mAdapter.notifyDataSetChanged();
                        } else {
                            changeStar(mAdapter, mSelectedStarModel);
                        }
                        break;
                    }
                }
            }
        }
    }


    public void changeDanmu(View view) {
        mCountTime = 0;
        if (mDanmakuView.isShown()) {
            mDanmakuView.hide();
            view.setSelected(false);
            Toast.makeText(getActivity(), getString(R.string.live_danmu_hide), Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getActivity(), getString(R.string.live_danmu_show), Toast.LENGTH_SHORT).show();
            view.setSelected(true);
            mDanmakuView.show();
        }
    }

    public void changeOnline(String changeStr) {
        Activity activity = getActivity();
        if (mViewHolder.mTvOnline != null && activity != null && !activity.isFinishing()) {
            Message message = new Message();
            message.what = WHAT_CHANGE_KEY_ON_LINE;
            Bundle bundle = new Bundle();
            bundle.putString("online", changeStr);
            message.setData(bundle);
            mHandler.sendMessage(message);
        }
    }


    public void changeStarHotValue(long changeStr) {
        if (mTvPopularityValuvalue != null) {
            mTvPopularityValuvalue.setText(changeStr + "");
        }
    }

    public void screenOrietantionChanged(boolean island) {
        mIsLandView = island;
        if (island) {
            if (mDanmakuView != null) {
                mDanmakuView.show();
            }
            mIbtnGift.setVisibility(View.VISIBLE);
            mIbtnMargin.setVisibility(View.INVISIBLE);
        } else {
            mLlPopularity.setVisibility(View.GONE);
            mIbtnGift.setVisibility(View.GONE);
            mIbtnMargin.setVisibility(View.GONE);
            if (mDanmakuView != null && mDanmakuView.isShown()) {
                mDanmakuView.hide();
            }
            mDanmuUtil.clearDanmu();
        }
        if (mIsDefaultView) {
            changeView(false);
        }
        changeLayouParams();
        setTagView(island);
        if (mLiveMsgView != null) {
            mLiveMsgView.changeScreenConfig();
        }
    }

    class ViewHolder {
        TextView mTvOnline;
        //        TextView mTvPlayingTime;
        LinearLayout mLlOnline;
        Button mBtnAttention;
        RelativeLayout mRlStarInfo;
        ImageView mIvIcon;
        TextView mTvName;
        ImageView mIvTag;
        TextView mTvRanking;
        TextView mTvRankingDistance;
        LinearLayout mLlRank;
        HorizontalListView mHlvStars;
        LinearLayout mLlSeekbar;
        ImageButton mIbtnPause;
        TextView mTvCurrTime;
        SeekBar mSeekbar;
        TextView mTvEndTime;
        FrameLayout mFlMsg;
    }


    public interface IVideoViewCallBcak {
        boolean changeTitle(boolean changeDisplay, boolean isClick);

        void changeStar(StarModel model);

        void showGift();
    }
}
